package com.wj.rspmproperty.service.impl;

import com.wj.rspmproperty.mapper.FloorMapper;
import com.wj.rspmproperty.mapper.RoomMapper;
import com.wj.rspmproperty.pojo.Floor;
import com.wj.rspmproperty.pojo.Room;
import com.wj.rspmproperty.service.FloorService;
import com.wj.rspmproperty.uitls.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author WeiJin
 * @version 1.0
 */
@Service
@Transactional
public class FloorServiceImpl implements FloorService {

    @Autowired
    private FloorMapper floorMapper;
    @Autowired
    private RoomMapper roomMapper;


    @Override
    public List<Floor> floorOfBuilding(Integer buildingId) {
        return floorMapper.floorOfBuilding(buildingId);
    }

    @Override
    public void insertFloors(Floor floor, Map<String, Integer> results, int size, Integer[] builtArea) {

        List<Floor> floorList = new ArrayList<>(size);
        int result = -1;
        //批量添加楼层
        try {
            for (int i = 0; i < size; i++) {
                Floor tempFloor = floor.clone();
                tempFloor.setFloor_number((short) (i + 1));
                floorList.add(tempFloor);
            }
            result = floorMapper.insertFloors(floorList);
            results.put("floor", results.get("floor") + result);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        //批量添加房间
        for (Floor f : floorList) {
            //给每个房间设置参数
            List<Room> list = Arrays.stream(builtArea).map(i -> {
                Room room = new Room();
                room.setRoom_floor_id(f.getFloor_id());
                room.setRoom_code(StringUtil.getNumberFromString(f.getBuilding_name()) + "-" + f.getFloor_number() + "-");
                room.setBuilt_up_area(i.shortValue());
                return room;
            }).collect(Collectors.toList());
            result = roomMapper.insertRooms(list);
            results.put("room", results.get("room") + result);
        }
    }
}
